from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
from app.models.base import Base

# 创建SQLite引擎
engine = create_engine(
    settings.SQLALCHEMY_DATABASE_URI,
    connect_args={
        "check_same_thread": False,  # SQLite特定配置
        "timeout": 30  # 增加连接超时时间
    },
    pool_pre_ping=True,  # 自动检测连接是否有效
    pool_recycle=3600,   # 每小时回收连接
    pool_size=5,         # 连接池大小
    max_overflow=10      # 最大溢出连接数
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def init_db():
    """初始化数据库"""
    # 导入所有模型以确保它们被注册到Base.metadata
    from app.models.learning import KnowledgeBase, Exercise, LearningPlan, LearningTask
    from app.models.user import User

    # 创建所有表
    Base.metadata.create_all(bind=engine)

    # 验证表是否创建成功
    inspector = inspect(engine)
    tables = inspector.get_table_names()
    print(f"Created tables: {tables}")

def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()